package com.zhuangyuan.cloud.web.controller;

import com.zhuangyuan.cloud.core.annotations.DefaultLayout;
import com.zhuangyuan.cloud.data.entities.Cate;
import com.zhuangyuan.cloud.data.entities.Category;

import com.zhuangyuan.cloud.data.service.CateService;
import com.zhuangyuan.cloud.data.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by 10191042 on 2019-08-05.
 */
@Controller
public class MenuController {
    private static Logger logger = LoggerFactory.getLogger(MenuController.class);

    @Autowired
    private CateService cateService;
    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/menu/list")
    public String getMenu(Model model){
        List<Cate> list = cateService.list();
        model.addAttribute("list",list);
        return "/menu/list";
    }

    @RequestMapping("/api/menu/list")
    @ResponseBody
    public List<Cate> getMenuJson(){
        List<Cate> list = cateService.list();

        return list;
    }

    @RequestMapping("/menu/add")
    public String add(){
        return "/menu/add";
    }

    @PostMapping("/menu/post")
    @Transactional(rollbackFor = Exception.class)
    public String post(HttpServletRequest request,
                       HttpServletResponse response,
                       Cate model) throws Exception {
        if(model != null){
            cateService.add(model);
        }

        return "redirect:/menu/list";

    }

    @RequestMapping("/")
    public String index(){
        logger.info("call MenuController index");
        logger.warn("call MenuController index");
        return "/menu/index";
    }

    @DefaultLayout
    @RequestMapping("/testlayout")
    public String testLayout(Model model) {
        return "/menu/testLayout";
    }

}
